/*
 * comPort.h
 *
 * Created: 6/23/2013 1:26:40 AM
 *  Author: Tim
 */ 


#ifndef COMPORT_H_
#define COMPORT_H_

#include <avr/io.h>
#include <avr/sfr_defs.h>
#include <avr/interrupt.h>
#include <stdio.h>

#define bufferSize	512

//115200
#define BAUD115200	2158
#define USART_BAUDCTRLA_115200	BAUD115200
#define USART_BAUDCTRLB_115200	0xA0 | (uint16_t)(0x0FFF & BAUD115200>>8)
#define USART_CTRLB_115200		USART_RXEN_bm | USART_TXEN_bm | USART_CLK2X_bm

//125000
#define BAUD125000	1984
#define USART_BAUDCTRLA_125000	BAUD125000
#define USART_BAUDCTRLB_125000	0xA0 | (uint16_t)(0x0FFF & BAUD125000>>8)
#define USART_CTRLB_125000		USART_RXEN_bm | USART_TXEN_bm | USART_CLK2X_bm

//230400
#define BAUD230400	2094
#define USART_BAUDCTRLA_230400	BAUD230400
#define USART_BAUDCTRLB_230400	0x90 | (uint16_t)(0x0FFF & BAUD230400>>8)
#define USART_CTRLB_230400		USART_RXEN_bm | USART_TXEN_bm | USART_CLK2X_bm

//1M
#define BAUD1M	384
#define USART_BAUDCTRLA_1M	BAUD1M
#define USART_BAUDCTRLB_1M	0x90 | (uint16_t)(0x0FFF & BAUD1M>>8)
#define USART_CTRLB_1M		USART_RXEN_bm | USART_TXEN_bm | USART_CLK2X_bm


//3M
#define BAUD3M	43
#define USART_BAUDCTRLA_3M	BAUD3M
#define USART_BAUDCTRLB_3M	0x90 | (uint16_t)(0x0FFF & BAUD3M>>8)
#define USART_CTRLB_3M		USART_RXEN_bm | USART_TXEN_bm | USART_CLK2X_bm


typedef struct{
	uint8_t *bufferBegin;
	uint8_t *bufferEnd;
	uint8_t *head;
	uint8_t *tail;
	uint8_t data[bufferSize];
}buf_t;

buf_t bufRxD1;
buf_t bufTxD1;


void comPortPut(uint8_t *packet,uint16_t packetLength);
  
uint8_t comPortGet(uint8_t *packet);

uint8_t bufferRead(buf_t *buffer);

void bufferWrite(buf_t *buffer, char c);

uint8_t dataInBuf(buf_t *buffer);

void comPortInit();

uint8_t timeOut();

void comPortPutC(uint8_t c);
uint8_t comPortGetC();

FILE USB_str;

#endif /* COMPORT_H_ */